#include "engine.h"
#include "window.h"
#include "game.h"

using namespace ns;


Engine::Engine(HINSTANCE hInstance, unsigned int uiWidth, unsigned int uiHeight){
	m_kWindow = NULL;
	m_pkRenderer = NULL;
	m_hInstance = hInstance;
	m_uiWidth = uiWidth;
	m_uiHeight = uiHeight;
}

bool Engine::init(){
	HWND hWnd = NULL;
	m_kWindow = new Window(m_hInstance);

	if(!m_kWindow)
		return false;

	m_kWindow->createWindow(800,600,hWnd);

	m_pkRenderer = new Renderer();
	m_pkRenderer->init(hWnd);
	dInput=new DirectInput();
	dInput->init(m_hInstance,hWnd);
	return true;
}

void Engine::SetGame(Game* _game){
	game = _game;
}

void Engine::run ()
{
	if(!game)
	{
		return;
	}

	// init game
	if( !game->init(*m_pkRenderer,*dInput) )
	{
		return;
	}
	
	// frame loop
	MSG kMsg;
	while( !game->isDone() )
	{
		m_pkRenderer->beginFrame();
		game->frame(*m_pkRenderer);
		m_pkRenderer->endFrame();

		if( PeekMessage(&kMsg, NULL, 0, 0, PM_REMOVE) )
		{
			// check if we have to exit the game
			switch(kMsg.message)
			{
				case WM_QUIT:
				{
					game->setDone(true);
					break;
				}
			}

			TranslateMessage(&kMsg);
			DispatchMessage(&kMsg);
		}
	}

	// deinitialization
	game->deinit();
}